Clipping shapefiles allows you to select certain features and attributes from a layer based on spatial extraction.
For example, you may be a public health analyst interested in studying the distribution of the locations providing seasonal flu vaccinations in an area. You might seek to answer the following questions: Are there enough locations providing flu vaccinations and are they equally distributed? Where can/should a new location be added? You now have a map of the locations providing seasonal flu vaccinations throughout New York City, but suppose you are focused on Manhattan, and don’t need to see the locations in the other four boroughs. Let’s conduct this analysis using Python and the geopandas package. You can use the read_file() method from the geopandas package to read the shapefile you wish to clip and the shapefile you will use to restrict the original shapefile, then convert the coordinate reference systems of the shapefiles to an appropriate one for the geography of your data by using the to_crs() method, and then use the clip() method to clip the original spatial layer based on the other layer.
If you already have Anaconda downloaded and installed, you can skip Part A and directly start the analysis in Part B. Make sure you also have packages pandas, geopandas of version 0.7 or higher, matplotlib, and descartes installed in the environment where you would like to conduct this analysis. Note starting with the version 0.7, geopandas made a big change in Coordinate Reference System representation and hence some code syntax differs before and after version 0.7, as described here and here. As our tutorial writes in new version syntax, please make sure your geopandas is of version 0.7 or later in order to run the code with no error. You may check the version of geopandas and upgrade it within your environment either in Anaconda Navigator or in your terminal window.
1) First, download Anaconda. Anaconda is a free and open-source distribution of Python. You can use Anaconda to install IDEs (integrated development environments where you can write and run code) and packages like Pandas and Geopandas. Go to the link to download Anaconda, https://www.anaconda.com/products/individual, and then open the .exe file that was downloaded and follow the instructions in the installation wizard prompt.
2) Once installation is complete, open Anaconda Navigator and create a new environment for your project. A Conda environment is a directory that contains a specific collection of Conda packages that you have installed. Conda has a default environment called 'base' that includes a Python installation and some core system libraries and dependencies of Conda. It is a “best practice” to avoid installing additional packages into your base environment, and, instead, create an isolated environment to manage packages and dependencies in a new project.
Click on the Environments selection in the left sidebar menu and then click on the 'Create' at the bottom. This will open a dialog box prompting you to create a name for the new environment. You can give any name for your new environment. Here, we use 'GIS_in_Python' as the environment name. Then click the 'Create' button within the dialog box to finish the creation.
3) Once you have your project environment set up, click on the arrow to the right of your new environment, 'GIS_in_Python' in this example, and select Open Terminal. This will give you access to the command line interface on your computer in a window.
4) Install the packages/libraries necessary for the analysis by entering the following commands in the opened terminal, one line at a time:
conda install pandas
conda install geopandas
conda install matplotlib
conda install descartes
5) Once you have those libraries all installed, select the new environment, 'GIS_in_Python' in this example, in the 'Applications on' dropdown menu, and then click "install" and "launch" under Jupyter Notebook. Jupyter Notebook will open in your web browser (it does not require the internet to work).
6) In Jupyter Notebook, navigate to the folder where you saved the code file you plan to use and open the .ipynb file (the extension for Jupyter Notebook files written in Python) to run it in the Notebook. If you would like to create a new .ipynb file, browse to the folder in which you would like to save your Notebook, then click the "New" dropdown button on the top-right and select "Python 3". Your new Notebook will open in a new tab in your browser. If you want to create a new directory using the Jupyter Notebook dashboard, click the "New" dropdown button and then select "Folder". To add files from your local machine, click the "Upload" button on the top-right to open a file chooser window and then choose the file you wish to upload.
1) Import necessary packages/libraries.
import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd
import descartes
2) Use the gpd.read_file() function from the geopandas package to read the shapefile. Optionally, you can use the head() method to return the first 5 rows of the GeoDataFrame, and use the .shape attribute to check the number of rows and columns of the GeoDataFrame in the returned tuple (number of rows, number of columns). For this example, the number of rows of the 'NYC_flu_vaccinations' and the 'Manhattan_tracts' suggest that there are 885 locations providing seasonal flu vaccinations in NYC and 288 census tracts in Manhattan.
NYC_flu_vaccinations = gpd.read_file("NYC_FluVaccinations.shp")
NYC_flu_vaccinations.head()
| OBJECTI | A | Srvc_Ct | Srvc_Ty | Walk_in | Insurnc | Childrn | Fclty_N | Address | City | ... | Tuesday | Wednsdy | Thursdy | Friday | Saturdy | Sunday | Mr_Infr | DOHMH_W | Locatin | geometry | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 646 | 748 | Vaccines | Flu Vaccine (Influenza) | Yes | Yes | No | Newtown Pharmacy | 28-04 31st Street | Astoria | ... | None | None | None | None | None | None | Call location for hours | http://www1.nyc.gov/site/doh/health/health-top... | (40.76832276, -73.92009603) | POINT (-73.92010 40.76832) |
| 1 | 70 | 224 | Vaccines | Flu Vaccine (Influenza) | Yes | Yes | No | Walgreens Drug Store | 84-20 Broadway | Queens | ... | None | None | None | None | None | None | Call location for hours | http://www1.nyc.gov/site/doh/health/health-top... | (40.73963768, -73.87819067) | POINT (-73.87819 40.73964) |
| 2 | 810 | 840 | Vaccines | Flu Vaccine (Influenza) | Yes | Yes | Yes | Homecrest Clinic | 1601 AVENUE S | BROOKLYN | ... | None | None | None | None | None | None | Call location for hours and information. Insur... | http://www1.nyc.gov/site/doh/health/health-top... | (40.60359817, -73.95620902) | POINT (-73.95621 40.60360) |
| 3 | 630 | 659 | Vaccines | Flu Vaccine (Influenza) | Yes | Yes | No | Medcare Health Inc. | 260 Kings Highway | Brooklyn | ... | None | None | None | None | None | None | Call location for hours | http://www1.nyc.gov/site/doh/health/health-top... | (40.60525733, -73.98105345) | POINT (-73.98105 40.60526) |
| 4 | 366 | 182 | Vaccines | Flu Vaccine (Influenza) | Yes | Yes | No | Duane Reade | 949 3RD AVE | NEW YORK | ... | None | None | None | None | None | None | Call location for hours | http://www1.nyc.gov/site/doh/health/health-top... | (40.76012276, -73.96758174) | POINT (-73.96758 40.76012) |
5 rows × 25 columns
Manhattan_tracts = gpd.read_file("Manhattan_tracts.shp")
Manhattan_tracts.head()
| STATEFP | COUNTYFP | TRACTCE | GEOID | NAME_x | NAMELSAD | MTFCC | FUNCSTAT | ALAND | AWATER | INTPTLAT | INTPTLON | NAME_y | geometry | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 36 | 061 | 023400 | 36061023400 | 234 | Census Tract 234 | G5020 | S | 108235.0 | 0.0 | +40.8237305 | -073.9386702 | Census Tract 234, New York County, New York | POLYGON ((-73.94097 40.82413, -73.94051 40.824... |
| 1 | 36 | 061 | 023501 | 36061023501 | 235.01 | Census Tract 235.01 | G5020 | S | 179045.0 | 0.0 | +40.8289967 | -073.9418352 | Census Tract 235.01, New York County, New York | POLYGON ((-73.94483 40.82902, -73.94438 40.829... |
| 2 | 36 | 061 | 023502 | 36061023502 | 235.02 | Census Tract 235.02 | G5020 | S | 41338.0 | 0.0 | +40.8278881 | -073.9389277 | Census Tract 235.02, New York County, New York | POLYGON ((-73.94014 40.82704, -73.93969 40.827... |
| 3 | 36 | 061 | 023600 | 36061023600 | 236 | Census Tract 236 | G5020 | S | 263158.0 | 127979.0 | +40.8242944 | -073.9356565 | Census Tract 236, New York County, New York | POLYGON ((-73.93960 40.82600, -73.93915 40.826... |
| 4 | 36 | 061 | 023700 | 36061023700 | 237 | Census Tract 237 | G5020 | S | 271911.0 | 273621.0 | +40.8343381 | -073.9551977 | Census Tract 237, New York County, New York | POLYGON ((-73.95861 40.83738, -73.95040 40.834... |
Let’s look at the shape of the shapefiles for 'NYC_flu_vaccinations' and 'Manhattan_tracts'.
print(NYC_flu_vaccinations.shape)
print(Manhattan_tracts.shape)
(885, 25) (288, 14)
You may also use matplotlib for plotting to generate an overview of your GeoDataFrame.
plt.subplots(), "fig" short for figure, and "ax" short for axes.figsize = (12,12), the first number corresponding to width, the X axis, and the second corresponding to height, the Y axis. ax = ax sets axes on which to draw the plot.
fig, ax = plt.subplots(figsize=(12, 12))
NYC_flu_vaccinations.plot(ax=ax)
<AxesSubplot:>
fig, ax = plt.subplots(figsize=(12, 12))
Manhattan_tracts.plot(ax=ax)
<AxesSubplot:>
3) Before clipping, use the .crs attribute to check the current Coordinate Reference System (CRS)/projection of your spatial datasets, and if they are not projected into the same coordinate reference system, use the to_crs() method to re-project the data to a projection appropriate for the geographical area of your data. This is because the geopandas package can only carry out a clipping between layers that are in the same projected coordinate.
In this example, 'NYC_flu_vaccinations' and 'Manhattan_tracts' are the two GeoDataFrame that we need to examine their projections (.crs). Since the CRS of the two GeoDataFrames are different, EPSG:4326 for the 'NYC_flu_vaccinations' and EPSG:4269 for the 'Manhattan_tracts', we must convert the CRS. A bit of research suggests that EPSG:2263 would be an appropriate projection for New York. Therefore, we convert the CRS of 'NYC_flu_vaccinations' and 'Manhattan_tracts' to EPSG:2263 (.to_crs('epsg:2263')).
For more information and resources on coordinate systems and map projections, please see Appendix 1 in NYU Data Services’ QGIS tutorial, which is available here.
NYC_flu_vaccinations.crs
<Geographic 2D CRS: EPSG:4326> Name: WGS 84 Axis Info [ellipsoidal]: - Lat[north]: Geodetic latitude (degree) - Lon[east]: Geodetic longitude (degree) Area of Use: - name: World - bounds: (-180.0, -90.0, 180.0, 90.0) Datum: World Geodetic System 1984 - Ellipsoid: WGS 84 - Prime Meridian: Greenwich
Manhattan_tracts.crs
<Geographic 2D CRS: EPSG:4269> Name: NAD83 Axis Info [ellipsoidal]: - Lat[north]: Geodetic latitude (degree) - Lon[east]: Geodetic longitude (degree) Area of Use: - name: North America - NAD83 - bounds: (167.65, 14.92, -47.74, 86.46) Datum: North American Datum 1983 - Ellipsoid: GRS 1980 - Prime Meridian: Greenwich
NYC_flu_vaccinations = NYC_flu_vaccinations.to_crs('epsg:2263')
Manhattan_tracts = Manhattan_tracts.to_crs('epsg:2263')
4) Once the two GeoDataFrames have been converted into the same coordinate reference system, you can use the clip() method to clip the data to the boundary of the polygon layer that you select.
flu_vaccinations_clipped = gpd.clip(NYC_flu_vaccinations, Manhattan_tracts)
Optionally, by checking the .shape attribute of the new GeoDataFrame 'flu_vaccinations_clipped', the number of rows suggests that there are 315 locations providing seasonal flu vaccinations in Manhattan.
flu_vaccinations_clipped.shape
(315, 25)
5) Now you can generate a map with the clipped spatial object overlaying the object you use for clipping. Based on the map of 'Manhattan_tracts' we generated in Step 2, add the clipped flu vaccination location point layer, 'flu_vaccinations_clipped', on the same axes (ax=ax) with black color (color="black"). You will see only clipped features remain and you can now only study the area of your interest.
fig, ax = plt.subplots(figsize=(12, 12))
Manhattan_tracts.plot(ax=ax)
flu_vaccinations_clipped.plot(ax=ax, color = 'black')
<AxesSubplot:>